package com.wlzg.collectiontool.view

import android.Manifest
import android.app.Activity
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import android.view.View
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
import com.esri.arcgisruntime.data.TileCache
import com.esri.arcgisruntime.geometry.GeometryEngine
import com.esri.arcgisruntime.geometry.Point
import com.esri.arcgisruntime.geometry.PolygonBuilder
import com.esri.arcgisruntime.geometry.PolylineBuilder
import com.esri.arcgisruntime.layers.ArcGISTiledLayer
import com.esri.arcgisruntime.mapping.ArcGISMap
import com.esri.arcgisruntime.mapping.Basemap
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener
import com.esri.arcgisruntime.mapping.view.Graphic
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay
import com.esri.arcgisruntime.mapping.view.LocationDisplay
import com.esri.arcgisruntime.symbology.SimpleFillSymbol
import com.esri.arcgisruntime.symbology.SimpleLineSymbol
import com.esri.arcgisruntime.symbology.SimpleMarkerSymbol
import com.github.dfqin.grantor.PermissionListener
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.wlzg.collectiontool.App
import com.wlzg.collectiontool.R
import com.wlzg.collectiontool.map.TianDiTuTiledLayerClass
import com.wlzg.collectiontool.util.FileUtil
import com.wlzg.collectiontool.util.PermissionUtil
import com.wlzg.collectiontool.util.WifiUtil
import kotlinx.android.synthetic.main.fragment_manager.*
import java.text.NumberFormat

class ManageFragment : BaseMapFragment(), View.OnClickListener {
    var locationDisplay: LocationDisplay? = null
    protected val graphicsOverlay by lazy { GraphicsOverlay() }
    private val areaPoints by lazy { ArrayList<Point>() }
    private val linePoints by lazy { ArrayList<Point>() }
    private var daoluModel = false
    private var xiaoquModel = false
    private var xiangmuModel = false
    private var gongchengModel = false
    private var newPropop: BasePopupView? = null
    private var newGcpop: BasePopupView? = null
    private var newXqpop: BasePopupView? = null
    private var newDlpop: BasePopupView? = null
    private var xmlistPop: BasePopupView? = null
    private var gclistPop: BasePopupView? = null
    private var xqlistPop: BasePopupView? = null
    private var dllistPop: BasePopupView? = null
    private var enableDaolu: Boolean = false
    private var enableXiaoqu: Boolean = false
    var graphic:Graphic?=null
    var graphic1:Graphic?=null
    var lineGraphic:Graphic?=null
     var xmPoint:Point?=null
     var gcPoint:Point?=null
    var xmGraphic:Graphic?=null
    var gcGraphic:Graphic?=null
    var dlGraphic:Graphic?=null
    var xqGraphic:Graphic?=null

    override fun getLayoutId(): Int =
        R.layout.fragment_manager

    private fun initxmlistPop(){
        xmlistPop = XPopup.Builder(context).dismissOnTouchOutside(false).offsetY(100).offsetX(80)
            .asCustom(ProlistDia(requireContext(), this))
    }
    private fun initgclistPop(){
        gclistPop = XPopup.Builder(context).dismissOnTouchOutside(false).offsetY(100).offsetX(80)
            .asCustom(GclistDia(requireContext(), this))
    }
    private fun initxqlistPop(){
        xqlistPop = XPopup.Builder(context).dismissOnTouchOutside(false).offsetY(100).offsetX(80)
            .asCustom(XiaoqulistDia(requireContext(), this))
    }
    private fun initdllistPop(){
        dllistPop = XPopup.Builder(context).dismissOnTouchOutside(false).offsetY(100).offsetX(80)
            .asCustom(DaolulistDia(requireContext(), this))
    }

    override fun initView(container: View?, savedInstanceState: Bundle?) {
        super.initView(container, savedInstanceState)
        initMap()
        newPropop = XPopup.Builder(context).dismissOnTouchOutside(false).dismissOnBackPressed(false).offsetY(80)
            .isCenterHorizontal(true)
            .asCustom(NewXmDia(requireContext(), this,null))
        newGcpop = XPopup.Builder(context).dismissOnTouchOutside(false).dismissOnBackPressed(false).offsetY(80)
            .isCenterHorizontal(true)
            .asCustom(NewGcDia(requireContext(), this,null))
        newXqpop = XPopup.Builder(context).dismissOnTouchOutside(false).dismissOnBackPressed(false).offsetY(80)
            .isCenterHorizontal(true)
            .asCustom(NewXqDia(requireContext(), this,null))
        newDlpop = XPopup.Builder(context).dismissOnTouchOutside(false).dismissOnBackPressed(false).offsetY(80)
            .isCenterHorizontal(true)
            .asCustom(NewDlDia(requireContext(), this,null))

        xiangmu.setOnClickListener(this)
        gongcheng.setOnClickListener(this)
        daolu.setOnClickListener(this)
        xiaoqu.setOnClickListener(this)
        liebiao.setOnClickListener(this)
        xinjianxm.setOnClickListener(this)
        gcliebiao.setOnClickListener(this)
        xinjiangc.setOnClickListener(this)
        xinjiandl.setOnClickListener(this)
        dlliebiao.setOnClickListener(this)
        xinjianxq.setOnClickListener(this)
        xqlibiao.setOnClickListener(this)
        scaleup.setOnClickListener(this)
        scaledowm.setOnClickListener(this)
        location.setOnClickListener(this)
        initListener()
    }
    private fun initMap() {
        ArcGISRuntimeEnvironment.setLicense("runtimelite,1000,rud4449636536,none,NKMFA0PL4S0DRJE15166")
        mapView.isAttributionTextVisible = false
        var basemap:Basemap?=null
        if(!WifiUtil.isNetworkConnected(App.mContext)){
            val path = FileUtil.getSDPath()+"/map/yudu_basemap.tpk"
            val titleCache = TileCache(path)
            val arcGISTiledLayer =  ArcGISTiledLayer(titleCache)
             basemap = Basemap(arcGISTiledLayer)
        }else{
        //默认底图
        val webTiledLayer =
            TianDiTuTiledLayerClass.CreateTianDiTuTiledLayer(
                TianDiTuTiledLayerClass.LayerType.TIANDITU_VECTOR_MERCATOR
            )
        //标注
        val webTiledLayerLable =
            TianDiTuTiledLayerClass.CreateTianDiTuTiledLayer(
                TianDiTuTiledLayerClass.LayerType.TIANDITU_VECTOR_MERCATOR_LABLE
            )
        basemap = Basemap()
        basemap.baseLayers.add(webTiledLayer)
        basemap.baseLayers.add(webTiledLayerLable)
        }
        val arcGISMap = ArcGISMap(basemap)
        mapView.map = arcGISMap
        mapView.graphicsOverlays.add(graphicsOverlay)
        PermissionUtil.requestPermission(
            context as Activity?, arrayOf<String>(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA

            ),object : PermissionListener {
                override fun permissionGranted(permission: Array<out String>) {
                    locationDisplay = mapView.locationDisplay
                    locationDisplay?.isShowLocation = true
                    locationDisplay?.isShowPingAnimation = true
                    locationDisplay?.isShowAccuracy = true
                    locationDisplay?.autoPanMode = LocationDisplay.AutoPanMode.OFF
                    locationDisplay?.startAsync()
                }

                override fun permissionDenied(permission: Array<out String>) {

                }

            })



//        tvScale.text = "${mapView.mapScale}"
    }

    private fun initListener() {
        mapView.onTouchListener = object : DefaultMapViewOnTouchListener(context, mapView) {
            override fun onSingleTapConfirmed(e: MotionEvent): Boolean {
                if (mapView.callout != null && mapView.callout.isShowing) {
                    mapView.callout.dismiss()
                }
                if (xiaoquModel) {
                    val point =
                        android.graphics.Point(e.x.toInt(), e.y.toInt())
                    val point1: Point = mapView.screenToLocation(point)
                    areaPoints.add(point1)
                    if (areaPoints.size == 1) {
                        val pointSymbol = SimpleMarkerSymbol(
                            SimpleMarkerSymbol.Style.SQUARE,
                            Color.argb(128, 0, 255, 255),
                            5F
                        )
                        graphic1 = Graphic(point1, pointSymbol)
                        graphicsOverlay.graphics.add(graphic1)
                    } else if (areaPoints.size == 2) {
                        val lineGeometry = PolylineBuilder(mapView.spatialReference)
                        lineGeometry.addPoints(areaPoints)
                        val lineSymbol = SimpleLineSymbol(
                            SimpleLineSymbol.Style.SOLID,
                            Color.argb(128, 0, 255, 255),
                            5F
                        )
                         lineGraphic = Graphic(lineGeometry.toGeometry(), lineSymbol)
                        graphicsOverlay.graphics.add(lineGraphic)
                    } else {
                        enableXiaoqu = true
                        graphicsOverlay.graphics.remove(graphic1)
                        graphicsOverlay.graphics.remove(lineGraphic)
                    }
                    val polygonGeometry = PolygonBuilder(mapView.spatialReference)
                    polygonGeometry.addPoints(areaPoints)
                    val polygonSymbol = SimpleFillSymbol(
                        SimpleFillSymbol.Style.SOLID,
                        Color.argb(128, 0, 255, 255),
                        null
                    )
                    val area = GeometryEngine.area(polygonGeometry.toGeometry())
                    val numberFormat = NumberFormat.getInstance()
                    numberFormat.maximumFractionDigits = 2
                    val s = numberFormat.format(area)
                    xqGraphic = Graphic(polygonGeometry.toGeometry(), polygonSymbol)
                    xqGraphic!!.attributes["value"] = "面积：$s 平方米"
                    graphicsOverlay.graphics.add(xqGraphic)
                } else if (daoluModel) {
                    val point =
                        android.graphics.Point(e.x.toInt(), e.y.toInt())
                    val point1: Point = mapView.screenToLocation(point)
                    linePoints.add(point1)
                    if (linePoints.size == 1) {
                        val pointSymbol = SimpleMarkerSymbol(
                            SimpleMarkerSymbol.Style.SQUARE,
                            Color.RED,
                            2F
                        )
                         graphic = Graphic(point1, pointSymbol)
                        graphicsOverlay.graphics.add(graphic)
                    } else {
                        enableDaolu = true
                        graphicsOverlay.graphics.remove(graphic)
                    }
                    val lineGeometry = PolylineBuilder(mapView.spatialReference)
                    lineGeometry.addPoints(linePoints)
                    val lineSymbol = SimpleLineSymbol(
                        SimpleLineSymbol.Style.SOLID,
                        Color.RED,
                        2F
                    )
                    val length = GeometryEngine.length(lineGeometry.toGeometry())
                    val numberFormat = NumberFormat.getInstance()
                    numberFormat.maximumFractionDigits = 2
                    val s = numberFormat.format(length)
                    dlGraphic = Graphic(lineGeometry.toGeometry(), lineSymbol)
                    dlGraphic!!.attributes["value"] = "长度：$s 米"
                    graphicsOverlay.graphics.add(dlGraphic)
                } else if (xiangmuModel) {
                    val point =
                        android.graphics.Point(e.x.toInt(), e.y.toInt())
                    val point1: Point = mapView.screenToLocation(point)
                    xmPoint=point1
                    Log.e("test", point1.toString())
                    // 生成一个红色圆形标识
                    val pointSymbol = SimpleMarkerSymbol(
                        SimpleMarkerSymbol.Style.CIRCLE,
                        Color.RED,
                        10F
                    )
                     xmGraphic = Graphic(point1, pointSymbol)
                    xmGraphic!!.attributes["value"] = "graphic：${(Math.random() * 10).toInt()}"
                    graphicsOverlay.graphics.add(xmGraphic)

                    if (!newPropop?.isShow!!) {
                        newPropop?.show()
                    }
                }else if (gongchengModel) {
                    val point =
                        android.graphics.Point(e.x.toInt(), e.y.toInt())
                    val point1: Point = mapView.screenToLocation(point)
                    gcPoint=point1
                    Log.e("test", point1.toString())
                    // 生成一个红色圆形标识
                    val pointSymbol = SimpleMarkerSymbol(
                        SimpleMarkerSymbol.Style.CIRCLE,
                        Color.RED,
                        10F
                    )
                    gcGraphic = Graphic(point1, pointSymbol)
                    gcGraphic!!.attributes["value"] = "graphic：${(Math.random() * 10).toInt()}"
                    graphicsOverlay.graphics.add(gcGraphic)

                    if (!newGcpop?.isShow!!) {
                        newGcpop?.show()
                    }
                }

                return super.onSingleTapConfirmed(e)
            }

            override fun onDoubleTap(e: MotionEvent?): Boolean {
                if (enableDaolu) {
                    enableDaolu = false
                    linePoints.clear()
                    if (!newDlpop?.isShow!!) {
                        newDlpop?.show()
                    }
                } else if (enableXiaoqu) {
                    enableXiaoqu = false
                    areaPoints.clear()
                    if (!newXqpop?.isShow!!) {
                        newXqpop?.show()
                    }
                }
                return false
            }
        }
    }

    private fun switchModel(view: View,view1: View) {
        clearModel()
        xiangmu.isSelected = false
        gongcheng.isSelected = false
        daolu.isSelected = false
        xiaoqu.isSelected = false
        view.isSelected = true
        daolul.visibility = View.INVISIBLE
        xiaoqul.visibility = View.INVISIBLE
        gongchengl.visibility = View.INVISIBLE
        mxiangmul.visibility = View.INVISIBLE
        view1.visibility = View.VISIBLE

    }

    fun ondelete(type :Int,obj:Any?){
        when(type){
            1->{
                graphicsOverlay.graphics.remove(xmGraphic)
//               obj.let {
//                   obj as PsXiangmu
//                   lifecycleScope.launch(context = Dispatchers.IO) {
//                       AppDatabase.getInstance().userDao().deleteXm(obj)
//                   }
//               }

            }
            2->{
                graphicsOverlay.graphics.remove(gcGraphic)
//                obj.let {
//                    obj as PsGongcheng
//                    lifecycleScope.launch(context = Dispatchers.IO) {
//                        AppDatabase.getInstance().userDao().deleteGc(obj)
//                    }
//                }
            }
            3->{
                graphicsOverlay.graphics.remove(dlGraphic)
//                obj.let {
//                    obj as PsDaolu
//                    lifecycleScope.launch(context = Dispatchers.IO) {
//                        AppDatabase.getInstance().userDao().deleteDl(obj)
//                    }
//                }
            }
            4->{
                graphicsOverlay.graphics.remove(xqGraphic)
//                obj.let {
//                    obj as PsXiaoqu
//                    lifecycleScope.launch(context = Dispatchers.IO) {
//                        AppDatabase.getInstance().userDao().deleteXq(obj)
//                    }
//                }
            }
        }
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.xiangmu -> {
                switchModel(xiangmu,mxiangmul)
            }
            R.id.gongcheng -> {
                switchModel(gongcheng,gongchengl)

            }
            R.id.daolu -> {
                switchModel(daolu,daolul)

            }
            R.id.xiaoqu -> {
                switchModel(xiaoqu,xiaoqul)
            }
            R.id.xinjianxm -> {
                clearModel()
                xiangmuModel = true

            }
            R.id.liebiao -> {
                clearModel()
                initxmlistPop()
                if (!xmlistPop?.isShow!!) {
                    xmlistPop?.show()
                }
            }
            R.id.xinjiangc -> {
                clearModel()
                gongchengModel = true
            }
            R.id.gcliebiao -> {
                clearModel()
                initgclistPop()
                if (!gclistPop?.isShow!!) {
                    gclistPop?.show()
                }
            }
            R.id.xinjiandl -> {
                clearModel()
                daoluModel = true
            }
            R.id.dlliebiao -> {
                clearModel()
                initdllistPop()
                if (!dllistPop?.isShow!!) {
                    dllistPop?.show()
                }
            }
            R.id.xinjianxq -> {
                clearModel()
                xiaoquModel = true
            }
            R.id.xqlibiao -> {
                clearModel()
                initxqlistPop()
                if (!xqlistPop?.isShow!!) {
                    xqlistPop?.show()
                }
            }
            R.id.location -> {
                if (locationDisplay?.autoPanMode == LocationDisplay.AutoPanMode.OFF) {
                    locationDisplay?.autoPanMode = LocationDisplay.AutoPanMode.RECENTER
                }

            }
            R.id.scaleup -> {
                mapView.setViewpointScaleAsync(mapView.mapScale * 0.5)

            }
            R.id.scaledowm -> {
                mapView.setViewpointScaleAsync(mapView.mapScale * 2)

            }
        }
    }

    private fun clearModel() {
        daoluModel = false
        xiaoquModel = false
        xiangmuModel = false
        gongchengModel = false
        enableDaolu = false
        enableXiaoqu = false
    }
}